package com.example.springbott.typeHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @descriptio: TODO string--string[]
 * @params:
 * @return:
 * @author: HeXiangZhi
 * @date: 2022/11/20 15:29
 */
@MappedTypes(String[].class)//java类型
@MappedJdbcTypes(JdbcType.VARCHAR)//数据库类型
public class StringArrayTypeHandler implements TypeHandler<String[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] integers, JdbcType jdbcType) throws SQLException {
        String value = objectMapper.writeValueAsString(integers);//也可以用Gson
        preparedStatement.setString(i,value);
    }

    @Override
    public String[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public String[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);
        return transfer(result);
    }

    @SneakyThrows
    private String[] transfer(String result) {
        String[] array = new String[0];
        if (result == null || "".equals(result)) {
            return array;
        }
        array = objectMapper.readValue(result, String[].class);
        return array;
    }
}
